package com.xiaozhengkeji.bukkit.chunkmanager;

import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 区块管理器服务层
 */
public class ChunkManagerService {
    public static Long MAX_CHUNK_SIZE = 0L;
    public static List<UUID> MANAGER_WORLD_LIST = new LinkedList<>();
    public static List<ChunkRunTickEntity> RUN_TICK_LOG = new LinkedList<>();
    public static FileConfiguration PLUGINS_CONFIG;

    public static HashMap<World, List<Chunk>> UN_CHUNK_MAP = new HashMap<>();

    public static Boolean TaskLock = false;

    public static void runChunkUninstallTask() {
        Long currentChunkSize = 0L;
        if (TaskLock) {
            MessageUtil.server("已经存在区块卸载任务");
            return;
        }
        TaskLock = true;

        UN_CHUNK_MAP.clear();//清空旧数据


        for (World world : Bukkit.getWorlds()) {
            //存在区块管理器
            if (MANAGER_WORLD_LIST.contains(world.getUID())) {
                List<Chunk> unChunkList = new LinkedList<>();
                for (Chunk chunk : world.getLoadedChunks()) {
                    if (currentChunkSize >= MAX_CHUNK_SIZE) {
                        continue;//超出限制直接跳过
                    }
                    //判断有无实体
                    if (chunk.getEntities().length < 1) {
                        //添加到卸载队列  并且安全的卸载
                        unChunkList.add(chunk);
                        currentChunkSize++;
                    }
                }
                UN_CHUNK_MAP.put(world, unChunkList);
            }
        }

        for (World world : UN_CHUNK_MAP.keySet()) {
            for (Chunk chunk : UN_CHUNK_MAP.get(world)) {
                world.unloadChunk(chunk);
            }
        }

        RUN_TICK_LOG.add(new ChunkRunTickEntity(currentChunkSize, new Date().toString()));
        TaskLock = false;
        MessageUtil.server("区块卸载任务执行完毕 本次共卸载了" + currentChunkSize + "个区块");
    }

    public static void loadConfig() {
        PLUGINS_CONFIG = ChunkManager.Main.getConfig();
        MAX_CHUNK_SIZE = PLUGINS_CONFIG.getLong("MAX_CHUNK_SIZE");
        for (String worldData : PLUGINS_CONFIG.getStringList("world")) {
            MANAGER_WORLD_LIST.add(UUID.fromString(worldData));
        }
    }
}
